import React, { useState } from 'react';
import { Modal, Form, Button, Toast } from 'antd-mobile';
import { useUserStore } from '../store/userStore';
import { useNavigate } from 'react-router-dom';
import { clearAuthData } from '../utils/storage';
import {  getIsPerpetualVip } from '../utils/storage';

const MembershipRedeem = ({ visible, onClose }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [exchangeCode, setExchangeCode] = useState('');
  const navigate = useNavigate();
  const { redeemMembership } = useUserStore();

  const handleSubmit = async () => {
  if (getIsPerpetualVip()) {
    Toast.show({
      content: '已是永久会员且不可兑换',
      position: 'center',
    });
    return;
  }
    if (!exchangeCode || exchangeCode.trim() === '') {
      Toast.show({
        content: '请输入兑换码',
        position: 'center',
      });
      return;
    }

    setLoading(true);
    try {
      const result = await redeemMembership(exchangeCode.trim());
      
      if (result.success) {
        Toast.show({
          content: result.message || '会员兑换成功',
          position: 'center',
          duration: 2000,
        });
        
        // 延迟后刷新页面并跳转到登录页
        setTimeout(() => {
          clearAuthData();
          navigate('/login');
        }, 2000);
      } else {
        Toast.show({
          content: result.message || '兑换失败',
          position: 'center',
        });
      }
    } catch (error) {
      console.error('兑换失败:', error);
      Toast.show({
        content: error.message || '兑换码无效',
        position: 'center',
      });
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setExchangeCode('');
    onClose();
  };

  const handleInputChange = (e) => {
    setExchangeCode(e.target.value);
  };

  return (
    <>
      <style>
        {`
          .membership-input::placeholder {
            font-size: 0.16rem !important;
            color: #999 !important;
            font-weight: normal !important;
          }
          .membership-input {
            font-size: 0.2rem !important;
          }
        `}
      </style>
      <Modal
        visible={visible}
        onClose={handleClose}
        title={
          <div style={{ 
            fontSize: '0.28rem', 
            fontWeight: '600',
            textAlign: 'center',
            color: '#333',
            padding: '0.2rem 0'
          }}>
            会员兑换
          </div>
        }
        content={
          <div style={{ 
            padding: '0.2rem 0.15rem',
            minHeight: 'auto'
          }}>
            <div style={{
              marginBottom: '0.2rem'
            }}>
              <input
                type="text"
                placeholder="请输入"
                value={exchangeCode}
                onChange={handleInputChange}
                className="membership-input"
                style={{
                  width: '100%',
                  height: '0.5rem',
                  fontSize: '0.2rem',
                  borderRadius: '0.1rem',
                  border: '1px solid #e5e7eb',
                  padding: '0 0.1rem',
                  backgroundColor: '#fafafa',
                  boxSizing: 'border-box',
                  outline: 'none',
                  marginBottom: '0.2rem',
                  fontFamily: 'inherit'
                }}
              />
            </div>
            
            <div style={{ 
              display: 'flex', 
              gap: '0.1rem', 
              marginTop: '0.15rem'
            }}>
              <Button
                onClick={handleClose}
                style={{
                  flex: 1,
                  height: '0.5rem',
                  fontSize: '0.22rem',
                  backgroundColor: '#f3f4f6',
                  color: '#6b7280',
                  border: '1px solid #d1d5db',
                  borderRadius: '0.1rem',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  whiteSpace: 'nowrap',
                  minWidth: '0'
                }}
              >
                取消
              </Button>
              <Button
                onClick={handleSubmit}
                loading={loading}
                style={{
                  flex: 1,
                  height: '0.5rem',
                  fontSize: '0.22rem',
                  backgroundColor: '#667eea',
                  color: 'white',
                  border: 'none',
                  borderRadius: '0.1rem',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  whiteSpace: 'nowrap',
                  minWidth: '0'
                }}
              >
                兑换
              </Button>
            </div>
          </div>
        }
        style={{
          borderRadius: '0.15rem',
          overflow: 'hidden',
          maxWidth: '70vw',
          width: '6rem'
        }}
      />
    </>
  );
};

export default MembershipRedeem; 